mod base;
mod callback;
mod kpi;
mod page_service;
// mod scan_image;
// mod pdf_reader;
pub mod chart_series;
pub mod home_page;
mod shhr;
mod zhzjfp;

pub use base::*;
pub use kpi::*;
pub use page_service::*;
// pub use pdf_reader::*;
pub use shhr::*;
pub use zhzjfp::*;

#[cfg(test)]
mod tests {
    use serde_json::{Map, Value};
    use shq_common::prelude::{get_import_template, get_page_config, get_redis_cli, ExcelReader};
    use shq_common::prelude::{
        report::DisplayCols, AndOr, Direction, OrderItems, WhereCause, WhereCauses,
    };
    use std::vec;
    use tracing::level_filters::LevelFilter;
    use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, Layer};

    use crate::chart_series::get_chart_with_dataset;
    use crate::page_service::PageService;
    use crate::{base, create_dept_approvers, create_home_visit_flow, kpi_import_conf_name};
    use std::fs::File;
    use std::io::Write;
    async fn init_config() -> base::Result<()> {
        dotenv::dotenv().ok();
        let stdout_log = tracing_subscriber::fmt::layer().pretty();
        tracing_subscriber::registry()
            .with(stdout_log.with_filter(LevelFilter::DEBUG))
            .init();
        base::init().await;
        Ok(())
    }
    #[tokio::test]
    async fn test_get_home_card_nums() {
        use crate::home_page::HomeNumberCards;
        init_config().await.unwrap();
        let home_cards = HomeNumberCards::load_from_cache().await;
        assert_eq!(home_cards.is_ok(), true);
        match home_cards {
            Err(err) => {
                println!("错误信息：{}", err);
            }
            Ok(cards) => {
                println!(
                    "lr_zb:{:?}, ck_zb:{:?}, dk_zb:{:?}, ybspm_zb:{:?}",
                    cards.get_lr_zb(),
                    cards.get_ck_zb(),
                    cards.get_dk_zb(),
                    cards.get_ybspm_zb()
                );
            }
        }
    }
    #[tokio::test]
    async fn test_hr_flow_create() {
        init_config().await.unwrap();
        let res = create_dept_approvers(202503, 3, 1120, vec![31001, 31011]).await;
        if let Err(err) = &res {
            println!("错误信息：{}", err);
        }
        let res = create_home_visit_flow(202503, 0, vec![31001, 31011, 31021]).await;
        if let Err(err) = &res {
            println!("错误信息：{}", err);
        }
        assert_eq!(res.is_ok(), true);
    }
    #[tokio::test]
    async fn test_find() {
        init_config().await.unwrap();
        // let mut wc = WhereCause::new("name".to_owned(), AndOr::And);
        // wc.add_filter_item(shq_common::prelude::Operator::Like, Some("支行".to_owned()));
        let mut wc = WhereCause::new("position_id".to_owned(), AndOr::And);
        wc.add_filter_item(shq_common::prelude::Operator::Like, Some("员工".to_owned()));
        let wcs = WhereCauses::from(vec![wc]);
        let ois = OrderItems::from_field("type_id", Direction::Asc);
        let ps = PageService::new("user", 0, 101);
        let res = ps
            .get_list_data(Some(wcs), Some(ois), DisplayCols::Default, 1, 20, None)
            .await;
        if let Err(err) = &res {
            println!("错误信息：{}", err);
        }
        println!("查询结果：{:?}", res.as_ref().unwrap());
        assert_eq!(res.is_ok(), true);
    }
    #[tokio::test]
    async fn test_insert() {
        init_config().await.unwrap();
        let mut row_data: Map<String, Value> = Map::new();
        row_data.insert("no".to_owned(), Value::from("test08"));
        row_data.insert("name".to_owned(), Value::from("测试08"));
        row_data.insert("desc".to_owned(), Value::from("测试测试08"));
        row_data.insert("parent_id".to_owned(), Value::from(0));
        row_data.insert("type_id".to_owned(), Value::from(1));
        row_data.insert("order_no".to_owned(), Value::from(3000));
        let ps = PageService::new("organ", 0, 101);
        let res = ps.save_row_data(row_data).await;
        if let Err(err) = &res {
            println!("错误信息：{}", err);
        }
        assert_eq!(res.is_ok(), true);
    }
    #[tokio::test]
    async fn test_update() {
        use redis::Commands;
        init_config().await.unwrap();
        let mut row_data: Map<String, Value> = Map::new();
        row_data.insert("id".to_owned(), Value::from(620034));
        row_data.insert("no".to_owned(), Value::from("test08"));
        row_data.insert("name".to_owned(), Value::from("测试用户08"));
        row_data.insert("desc".to_owned(), Value::from("测试测试测试08"));
        row_data.insert("parent_id".to_owned(), Value::from(0));
        row_data.insert("type_id".to_owned(), Value::from(1));
        row_data.insert("order_no".to_owned(), Value::from(3000));
        let ps = PageService::new("organ", 0, 101);
        let res = ps.save_row_data(row_data).await;
        if let Err(err) = &res {
            println!("错误信息：{}", err);
        }
        assert_eq!(res.is_ok(), true);
        let mut conn = get_redis_cli().get_connection().unwrap();
        let name: String = conn.hget("tch:sys_organization:620034", "name").unwrap();
        assert_eq!(name, "测试用户08");
    }
    #[tokio::test]
    async fn test_delte() {
        init_config().await.unwrap();
        let ps = PageService::new("organ", 0, 101);
        let res = ps.delete_by_ids(&[620034]).await;
        if let Err(err) = &res {
            println!("错误信息：{}", err);
        }
        assert_eq!(res.is_ok(), true);
    }
    #[tokio::test]
    async fn test_import() {
        init_config().await.unwrap();
        let mut paras_map: std::collections::HashMap<String, String> =
            std::collections::HashMap::new();
        let ps = PageService::new("kpi_import_pjzb", 0, 101);
        let ei =
            ExcelReader::from_file_name("零售分管_个贷_新增不良资产-大零售（打分表）.xls").unwrap();
        paras_map.insert("jd".to_string(), 20253.to_string());
        paras_map.insert("zbid".to_string(), 108.to_string());
        let res = ps.import_excel(paras_map, &ei).await;
        if let Err(err) = &res {
            println!("错误信息：{}", err);
        }
        assert_eq!(res.is_ok(), true);
    }
    #[tokio::test]
    async fn test_import_temple() {
        init_config().await.unwrap();
        let conf = get_page_config("organ").unwrap();
        let imp_conf = conf.import_props.as_ref().unwrap();
        let res = get_import_template(imp_conf, &conf.field_props);
        if let Err(err) = &res {
            println!("错误信息：{}", err);
        }
        assert_eq!(res.is_ok(), true);
    }
    #[tokio::test]
    async fn test_export() {
        init_config().await.unwrap();
        let mut wc = WhereCause::new("type_id__dict".to_owned(), AndOr::And);
        wc.add_filter_item(shq_common::prelude::Operator::Like, Some("支行".to_owned()));
        let wcs = WhereCauses::from(vec![wc]);
        let ois = OrderItems::from_field("order_no", Direction::Asc);
        let ps = PageService::new("organ", 0, 101);
        let res = ps
            .export_excel(DisplayCols::Default, Some(wcs), Some(ois))
            .await;
        if let Err(err) = &res {
            println!("错误信息：{}", err);
        } else if let Ok(data) = &res {
            let mut file = File::create("test.xlsx").expect("Failed to create file");
            file.write_all(data).expect("Failed to write data to file");
            println!("Successfully wrote data to test.xlsx");
        }
        assert_eq!(res.is_ok(), true);
    }

    #[tokio::test]
    async fn kpi_import_conf_name_test() {
        init_config().await.unwrap();
        let res1 = kpi_import_conf_name(20253, "新增不良资产-大公司").await;
        let res2 = kpi_import_conf_name(20253, "零售中收").await;
        match res1 {
            Ok(vec) => {
                assert!(!vec.is_empty(), "返回的向量应该是非空的");
            }
            Err(err) => {
                println!("错误信息：{}", err);
            }
        }
        match res2 {
            Ok(vec) => {
                assert!(!vec.is_empty(), "返回的向量应该是非空的");
            }
            Err(err) => {
                println!("错误信息：{}", err);
            }
        }
    }
    #[tokio::test]
    async fn test_chart_series_data() {
        init_config().await.unwrap();
        let rept_name = "chart_typm_lines";
        let params = vec![];
        let cols = vec![
            "dwmc".to_owned(),
            "ny".to_owned(),
            "bz".to_owned(),
            "lb".to_owned(),
            "je".to_owned(),
        ];
        let rept = shq_report::ReportService::new(&rept_name, &params, 0, 901)
            .await
            .unwrap();
        let display_cols = DisplayCols::Part(cols);
        let datas = rept
            .get_data_list(None, None, display_cols, 0, vec![], None, 1, 10000)
            .await
            .unwrap();
        let row_datas = datas
            .data
            .into_iter()
            .filter_map(|v| match v {
                Value::Array(arr) => Some(arr),
                _ => None,
            })
            .collect::<Vec<Vec<Value>>>();
        let chart_res = get_chart_with_dataset(None, rept_name, row_datas);
        match &chart_res {
            Err(ref e) => {
                println!("错误信息：{}", e);
            }
            Ok(chart) => {
                println!("成功生成图表：{}", chart);
            }
        }
        assert_eq!(chart_res.is_ok(), true);
    }
}
